'use client';

import Avatar from '@/asset/avatar.png';
import { authClient } from '@/lib/auth-client';
import { cn } from '@/lib/utils';
import { useSocket } from '@/providers/socket-provider';
import { MESSAGE_EVENT, type Message } from '@/service/type/socket';
import dayjs from 'dayjs';
import { useCallback, useEffect, useState } from 'react';
import QueryImage from './query-image';
import SendMessage from './send-message';

export default function MessageBox({
  initMessages,
  toId,
}: {
  initMessages: Message[];
  toId: string;
}) {
  const { data: session } = authClient.useSession();
  const socket = useSocket();
  const [messages, setMessages] = useState(initMessages ?? []);

  useEffect(() => {
    socket?.on(MESSAGE_EVENT, (args: Message) =>
      setMessages((prev) => [...prev, args]),
    );
    return () => {
      socket?.off(MESSAGE_EVENT);
    };
  }, [socket]);

  return (
    <div>
      <div
        // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
        ref={useCallback(
          (e: HTMLDivElement) => {
            e?.scrollTo({
              behavior: 'smooth',
              top: e?.scrollHeight,
            });
          },
          [messages.length],
        )}
        className="space-y-5 max-h-[70vh] overflow-y-auto scrollbar-none"
      >
        {messages.map((message) => (
          <div
            key={message.content + message.createdAt}
            className={cn(
              'flex',
              message.user.id === session?.user.id && 'justify-end',
            )}
          >
            {message.user.id !== session?.user.id ? (
              <div className="flex gap-2">
                <QueryImage
                  imageKey={message.user.image ?? undefined}
                  defaultImage={Avatar}
                  wrapperClassName="w-10 h-10 "
                  imgClassName="w-full h-full object-cover rounded-full"
                />
                <div className="space-y-2">
                  <div className="flex gap-2 items-center">
                    <div className="text-sm">{message.user.name}</div>
                    <div className="text-xs text-muted-foreground">
                      {dayjs(message.createdAt).format('YYYY-MM-DD HH:mm:ss')}
                    </div>
                  </div>
                  <div className="bg-muted px-2 py-1 rounded-r-lg rounded-bl-lg w-fit max-w-[400px] break-words">
                    {message.content}
                  </div>
                </div>
              </div>
            ) : (
              <div className="flex gap-4">
                <div className="space-y-2">
                  <div className="flex gap-2 justify-end items-center">
                    <div className="text-xs text-muted-foreground">
                      {dayjs(message.createdAt).format('YYYY-MM-DD HH:mm:ss')}
                    </div>
                    <div className="text-sm">{message.user.name}</div>
                  </div>
                  <div className="flex justify-end">
                    <div className="bg-muted px-2 py-1 rounded-l-lg rounded-br-lg w-fit max-w-[400px] break-words">
                      {message.content}
                    </div>
                  </div>
                </div>
                <QueryImage
                  imageKey={message.user.image ?? undefined}
                  defaultImage={Avatar}
                  wrapperClassName="w-10 h-10"
                  imgClassName="w-full h-full rounded-full object-cover"
                />
              </div>
            )}
          </div>
        ))}
      </div>
      <SendMessage toId={toId} messages={messages} />
    </div>
  );
}
